package com.hoshiicloud.saleorder.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.QueryException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.saleorder.entity.CoinList;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.CoinListMapper;
import com.hoshiicloud.saleorder.service.CoinListService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 金币流水 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-03
 */
@Slf4j
@Service
public class CoinListServiceImpl extends ServiceImpl<CoinListMapper, CoinList> implements
        CoinListService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    private CoinList entity;

    /**
     * @param id
     * @return com.hoshiicloud.saleorder.entity.CoinList
     * @description: 根据id查询金币流水
     */
    @Override
    @Cacheable(cacheNames = "CoinList", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "销售订单-金币流水-查询金币流水 ")
    public CoinList getById(Long id) {
        return Optional.ofNullable(baseMapper.selectById(id))
                .orElseThrow(() -> new QueryException("无法找到金币流水记录"));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 新增金币流水
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "CoinList", allEntries = true)
    @Logable(authName = "销售订单-金币流水-新增金币流水")
    public boolean save(CoinList entity) {

        return Optional.ofNullable(entity).map(coinList -> {
            String id = idGeneratorService.queryGeneratorId();
            log.error("{}", id);
            if (StrUtil.isBlank(id)) {
                log.error("id生成异常");
                throw new ServiceException(CommonError.error("网络开小差啦~, 请重新尝试"));
            }

            coinList.setId(Long.parseLong(id));
            coinList.setCreatedTime(LocalDateTime.now());
            int row = baseMapper.insert(coinList);
            if (row <= 0) {
                log.error("新增金币流水失败");
                throw new ServiceException(CommonError.error("新增金币流水失败"));
            }
            return true;
        }).orElseThrow(() -> new ServiceException(CommonError.error("新增金币流水失败，保存对象为空")));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改金币流水
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "CoinList", allEntries = true)
    @Logable(authName = "销售订单-金币流水管理-修改金币流水")
    public boolean updateById(CoinList entity) {

        this.entity = entity;
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改金币流水失败"));
        }

        return true;
    }

    /**
     * @param queryWrapper
     * @return IPage
     * @description: 分页查询金币流水
     */
    @Override
    @Logable(authName = "销售订单-金币流水管理-分页查询金币流水")
    @Cacheable(cacheNames = "CoinList", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+T(com.hoshiicloud.common.utils.DigestUtils).md5(#key)")
    public IPage<CoinList> page(IPage<CoinList> page, Wrapper<CoinList> queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "CoinList", allEntries = true)
    @Logable(authName = "销售订单-金币流水管理-删除金币流水")
    public boolean deleteById(Long id) {

        CoinList entity = this.getById(id);
        return Optional.ofNullable(entity).map(coinList -> {
            coinList.setUpdatedTime(LocalDateTime.now()).setDeleted(1);
            int row = baseMapper.updateById(coinList);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("删除失败"));
            }
            return true;
        }).orElseThrow(() -> {
            log.error("删除金币流水异常, 无法找到金币流水记录");
            return new QueryException("删除金币流水异常, 无法找到金币流水记录");
        });
    }

    @Override
    @Cacheable(cacheNames = "CoinList", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "销售订单-金币流水管理-根据id集合查询金币流水")
    public List<CoinList> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }
}
